from flask import Blueprint,render_template,request,redirect,url_for,flash
from model.models import Desk
from fromVal.deskForm import DeskForm,UpdateDeskForm
from exts import db

bp = Blueprint('desk',__name__,url_prefix='/desk')


@bp.route("/")
def index():
    Desks = Desk.query.all()
    return render_template('desk/desk_index.html',Desks=Desks)


@bp.route("add_desk",methods=['POST','GET'])
def add_desk():
    if request.method == 'GET':
        return render_template("desk/add_desk.html")
    elif request.method == 'POST':
        form = DeskForm(request.form)
        # 表单校验成功
        if form.validate():
            desk_name = form.desk_name.data
            men = form.men.data
            desk = Desk(desk_name=desk_name,men=men)
            db.session.add(desk)
            db.session.commit()
            return redirect(url_for("desk.index"))
        else:
            for errors in form.errors.values():
                for error in errors:
                    flash(error)
            return redirect(url_for("desk.add_desk"))


@bp.route("/update_desk",methods=['POST','GET'])
def update_desk():
    desks = []
    if request.method == 'GET':
        return render_template("desk/update_desk.html",desks=desks)
    elif request.method == 'POST':
        form = UpdateDeskForm(request.form)
        if form.validate():
            desk_name = form.desk_name.data
            desks = Desk.query.filter(Desk.desk_name.contains(desk_name)).all()
            #print(desk_name)
            return render_template("desk/update_desk.html",desks=desks)
        else:
            for errors in form.errors.values():
                for error in errors:
                    flash(error)

            return redirect(url_for('desk.update_desk',desks=desks))


@bp.route("/update_desk_info",methods=['POST','GET'])
def update_desk_info():
    desk_id = request.args.get('desk_no')
    if request.method == 'GET':
        print(desk_id)
        desk = Desk.query.filter(Desk.desk_no==desk_id).first()
        return render_template("desk/update_desk_detail.html",desk=desk)
    elif request.method == 'POST':
        form = DeskForm(request.form)
        if form.validate():
            desk_name = form.desk_name.data
            men = form.men.data
            # desk_id = request.form.get('desk_no')
            desk = Desk.query.filter(Desk.desk_no==desk_id).first()
            desk.desk_name = desk_name
            desk.men = men
            db.session.commit()
            return redirect(url_for('desk.index'))
        else:
            for errors in form.errors.values():
                for error in errors:
                    flash(error)
            return redirect(url_for('desk.update_desk_info',desk_no=desk_id))